package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import com.alibaba.fastjson.TypeReference;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.MiLianQuickBindCard;
import com.jh.paymentchannel.pojo.MiLianQuickRegister;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.milian.bean.*;
import com.jh.paymentchannel.util.milian.utils.HttpHelper;
import com.jh.paymentchannel.util.milian.utils.ParamsUtil;
import com.jh.paymentchannel.util.milian.utils.SignUtil;
import com.jh.paymentchannel.util.milian.utils.XmlUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class MiLianQuickService{
    private static final Logger log = LoggerFactory.getLogger(MiLianQuickService.class);

    @Value("${payment.ipAddress}")
    private String ipAddress;

    @Autowired
    private TopupPayChannelBusiness topupPayChannelBusiness;

    @Autowired
    private Util util;

    @Autowired
    private BranchbankBussiness branchbankBussiness;

    @Autowired
    MilianQuickpageRequest milianQuickpageRequest;

    @Value("${mlquick.parent}")
    private String parent;

    @Value("${mlquick.key}")
    private String key;

    /*进件URL*/
    @Value("${milian.RegisterUrl}")
    private String RegisterUrl;

/*    交易URL
    private String MlQuickPayUrl = "http://220.160.118.218:8281/MyLandQuickPay/controller/pay";

    代付URL
    private String MlQuickDFUrl = "http://220.160.118.218:8280/WeChatPay/servlet/DfReq";

    绑卡查询
    private String MLCardInfoQueryURL = "http://220.160.118.218:8280/WeChatPay/servlet/CardInfoQuery";

    交易结果查询
    private String MLOrderQueryURL = "http://220.160.118.218:8280/WeChatPay/servlet/Query";

    商户余额查询URL
    private String MLMerchBalanceQueryURL = "http://220.160.118.218:8280/WeChatPay/servlet/MerchBalanceQuery";
*/
    /*绑卡URL*/
    @Value("${mlquick.bindCardUrl}")
    private String MLBindCardUrl;

    /**
     * RESP_CODE:
     *     CommonConstants.STATUS_VALID | CommonConstants.STATUS_INVALID | CommonConstants.FALIED
     */
    @Transactional
    public Map<String, String> miLianBindBankCard(String userId,String creditCardNumber, String brandId) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        log.info(" == 米联 milianQuick 绑卡接口请求开始 ==parent:"+parent);

        // 查询判断是否绑定过
        // ....
        /** 如果已经绑定成功过 直接返回 CommonConstants.STATUS_VALID*/
        //map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_VALID);

        MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId), creditCardNumber);

        MiLianQuickBindCard miLianQuickBindCard = topupPayChannelBusiness.getMiLianQuickBindCardByUseridAndBankCard(userId, creditCardNumber);

        if(miLianQuickBindCard != null){
            if(miLianQuickBindCard.getState().equalsIgnoreCase("Y")){
                log.info("米联绑卡成功,当前状态为state={}",miLianQuickBindCard.getState());
                map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_VALID);
                map.put(CommonConstants.RESP_MESSAGE, "已经绑过信用卡了");
                map.put("channel_type", "milian_quick");
                return map;
            }else if(miLianQuickBindCard.getState().equalsIgnoreCase("N")){
                log.info("米联绑卡不成功,准备查询米联绑卡结果,当前状态为state={}",miLianQuickBindCard.getState());
                HttpServletRequest request = null;
                map  = (Map<String, String>) milianQuickpageRequest.mlCardInfoQuery(request,userId,creditCardNumber);
                if(map.get(CommonConstants.RESP_CODE).equals(CommonConstants.SUCCESS)){
                    map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_VALID);
                    map.put(CommonConstants.RESP_MESSAGE, "已经绑过信用卡了");
                    map.put("channel_type", "milian_quick");
                    return map;
                }
            }
        }
/*
        if(miLianQuickRegister != null && miLianQuickRegister.getState().equalsIgnoreCase("Y")){
            map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_VALID);
            map.put(CommonConstants.RESP_MESSAGE, "已经绑过信用卡了");
            map.put("channel_type", "milian_quick");
            return map;
        }*/
        miLianQuickBindCard = new MiLianQuickBindCard();
        MilianBankCardBean milianBankCardBean = new MilianBankCardBean();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/bank/default/cardno";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("cardno", creditCardNumber);
        requestEntity.add("type", "0");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject;
        JSONObject resultObj;
        log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询银行卡信息有误");
            map.put("channel_type", "milian_quick");
            return map;
        }
        String mobile = resultObj.getString("phone"); // 预留信用卡手机号码
        String idcard = resultObj.getString("idcard");// 身份证号
        String userName = resultObj.getString("userName");// 用户姓名
        String cvn2 = resultObj.getString("securityCode");// cvn2
        String valid = resultObj.getString("expiredTime");// valid

        if (miLianQuickRegister == null) {
            log.error("查询米联进件 miLianQuickRegister出错");
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询进件信息有误");
            map.put("channel_type", "milian_quick");
            return map;
        }
        milianBankCardBean.setOrder_id(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        milianBankCardBean.setUser_type("02");
        milianBankCardBean.setUser_id(miLianQuickRegister.getMerchantNo());
        milianBankCardBean.setSign_type("03");
        milianBankCardBean.setBus_code("1011");
        milianBankCardBean.setCheck_type("01");
        milianBankCardBean.setAcct_no(creditCardNumber);
        milianBankCardBean.setPhone_no(mobile);
        milianBankCardBean.setId_no(idcard);
        milianBankCardBean.setName(userName);
        milianBankCardBean.setCvn2(cvn2);
        milianBankCardBean.setValid(valid);
        /*页面通知地址*/
		milianBankCardBean.setPage_url(ipAddress + "/v1.0/paymentchannel/bindcard/ml/return_call?useridbankcard="
				+ userId + "__" + creditCardNumber);

        String params = ParamsUtil.getBindCardParams(milianBankCardBean,miLianQuickRegister);
        log.info("== miLianBindBankCard = 发起请求参数:" + params);
        String respResult = HttpHelper.doHttp(MLBindCardUrl, HttpHelper.POST, "UTF-8", params, "60000");
        RequestMsg RM = new RequestMsg();
        XmlUtil xmlUtil = new XmlUtil();
        xmlUtil.XmlToBean(RM, respResult);
        log.info("milian_quick 绑卡接口返回结果== " + RM.getRESP_DESCR()+" code:" + RM.getRESP_CODE());
        log.info("milian_quick 绑卡接口返回结果String== " + respResult);
        // CODE: 0000或者 00 成功，0100请求成功， 其他失败 ?
        //                  0100 请求成功是什么状态
        if (RM.getRESP_CODE().equals("0000") || RM.getRESP_CODE().equals("00") || RM.getRESP_CODE().equals("0100")) {
            log.info("milian_quick绑卡 processing==code:" + RM.getRESP_CODE());
            SignUtil signUtil = new SignUtil();
            Boolean checkResult;
            //Boolean checkResult = signUtil.checkSIGN(RM,miLianQuickRegister);

            // 米联的 验签Util有问题 (user_type空指针)
            checkResult = true;
            log.info("milian_quick绑卡 ---- checkResult:" + checkResult);
            if (checkResult){
                /*银联HTML5*/
                String payInfo = RM.getPAY_INFO();
                //log.info("milian_quick绑卡 payInfo==={}",payInfo);
                if (payInfo != null) {
                    payInfo = payInfo.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    String returnHtml = URLDecoder.decode(payInfo, "UTF-8");
                    //map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                    map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_INVALID);
                    map.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
                    map.put("returnHtml", returnHtml);
                    map.put("channel_type", "milian_quick");
                    map.put("isurl", "0");

                    miLianQuickBindCard.setUserId(userId);
                    miLianQuickBindCard.setPhone(mobile);
                    miLianQuickBindCard.setIdCard(idcard);
                    miLianQuickBindCard.setBankCard(creditCardNumber);
                    miLianQuickBindCard.setState("Y");
                    topupPayChannelBusiness.createMiLianQuickBindCard(miLianQuickBindCard);

                    //log.info("请求绑卡接口成功返回 returnHtml==================={}", returnHtml);
                    return map;
                }else{
                    log.error("milian_quick绑卡 payInfo=IS_NULL");
                }
            } else {
                log.info("请求绑卡接口失败=======" + RM.getRESP_DESCR()+" :" + RM.getRESP_CODE());
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
                map.put("channel_type", "milian_quick");
            }
        }else{
            log.info("请求绑卡接口失败======" + RM.getRESP_DESCR() + " :" + RM.getRESP_CODE());
            try {
                log.info("pay-info======" + RM.getPAY_INFO());
            }catch (Exception e){}
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, RM.getRESP_DESCR());
            map.put("channel_type", "milian_quick");
        }
        return map;
    }

    public Map<String, String> mlQuickReister(String userId, String bankNumber, String channelTag, String brandId) throws Exception {
        log.info("米联代扣代还进件 mlQuickReister 自动检测新增或更新进件============");
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId),bankNumber);
            log.info("查询米联进件信息miLianQuickRegister={}",miLianQuickRegister);

            if (miLianQuickRegister != null) {
                // -- 查费率和代付费
                log.info("mlQuickReister--查费率================"+channelTag);
                URI uri = util.getServiceUrl("user", "error url request!");
                String url = uri.toString() + "/v1.0/user/channel/query";
                /**根据的渠道标识或去渠道的相关信息*/
                MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
                requestEntity.add("channel_tag", channelTag);
                RestTemplate restTemplate=new RestTemplate();
                String resultObjx = restTemplate.postForObject(url, requestEntity, String.class);
                log.info("接口/v1.0/user/channel/query--RESULT================"+resultObjx);
                JSONObject jsonObject =  JSONObject.fromObject(resultObjx);
                JSONObject resultObj  =  jsonObject.getJSONObject("result");
                String channelId  = resultObj.getString("id");

                /** 根据用户的信息获取用户的渠道费率 */
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/channel/rate/query/userid";
                /** 根据的渠道标识或去渠道的相关信息 */
                requestEntity = new LinkedMultiValueMap<String, String>();
                requestEntity.add("channel_id", channelId + "");
                requestEntity.add("user_id", userId + "");
                log.info("参数================" + requestEntity);

                String result = restTemplate.postForObject(url, requestEntity, String.class);
                log.info("RESULT================/v1.0/user/channel/rate/query/userid:" + result);
                jsonObject = JSONObject.fromObject(result);
                if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                    log.info("mlQuickReister====查用户费率失败" + result);
                    resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                    resultMap.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
                    return resultMap;
                }
                resultObj = jsonObject.getJSONObject("result");
                String rate = resultObj.getString("rate");
                String extraFee = resultObj.getString("extraFee");
                if (rate.equals(miLianQuickRegister.getDebitRate()) && extraFee.equals(miLianQuickRegister.getCountFee())) {
                    log.info("mlQuickReister====进件已经存在并且费率等没变化 - ok");
                    resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                    resultMap.put(CommonConstants.RESP_MESSAGE, "商户进件成功。");
                    return resultMap;
                }else{
                    log.info("mlQuickReister====进件已经存在 - - 修改信息 ");
                    resultMap = mlQuickReister(userId, bankNumber, channelTag, brandId, "M");
                }
            }else{
                log.info("mlQuickReister====新增进件 ");
                resultMap = mlQuickReister(userId, bankNumber, channelTag, brandId, "A");
            }

        } catch (Exception e2) {
            log.error("查询米联进件信息miLianQuickRegister ----- fail:" + e2.getMessage());
            // TODO Auto-generated catch block
            e2.printStackTrace();
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
            return resultMap;
        }

        return resultMap;
    }

    protected Map<String, String> mlQuickReister(String userId, String bankNumber, String channelTag, String brandId, String handleType) throws Exception {
        log.info(" === 米联进件 mlQuickReister== type:" + handleType + " ==parent:"+parent);
        Map<String, String> resultMap = new HashMap<String, String>();

        // -- 查费率和代付费
        log.info("mlQuickReister--查费率================"+channelTag);
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/channel/query";
        /**根据的渠道标识或去渠道的相关信息*/
        MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
        requestEntity.add("channel_tag", channelTag);
        RestTemplate restTemplate=new RestTemplate();
        String resultObjx = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("接口/v1.0/user/channel/query--RESULT================"+resultObjx);
        JSONObject jsonObject =  JSONObject.fromObject(resultObjx);
        JSONObject resultObj  =  jsonObject.getJSONObject("result");
        String channelId  = resultObj.getString("id");

        /** 根据用户的信息获取用户的渠道费率 */
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/channel/rate/query/userid";
        /** 根据的渠道标识或去渠道的相关信息 */
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("channel_id", channelId + "");
        requestEntity.add("user_id", userId + "");
        log.info("参数================" + requestEntity);

        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("RESULT================/v1.0/user/channel/rate/query/userid:" + result);
        jsonObject = JSONObject.fromObject(result);
        if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
            log.info("mlQuickReister====查用户费率失败" + result);
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
            return resultMap;
        }
        resultObj = jsonObject.getJSONObject("result");
        String rate = resultObj.getString("rate");
        String extraFee = resultObj.getString("extraFee");

        // --- check user
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/query/id";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("id", userId );
        restTemplate = new RestTemplate();
        JSONObject userResultObj;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            jsonObject = JSONObject.fromObject(result);
            userResultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("==========米联进件 mlQuickReister /v1.0/user/query/id查询用户异常===========" + e.getMessage());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "查询用户异常");
            return resultMap;
        }

        // 查询绑定的信用卡信息
        restTemplate = new RestTemplate();
        String bankName = null;
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("cardno", bankNumber);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
        JSONObject withdrawBankresultObj = null;
        try {
            jsonObject = JSONObject.fromObject(result);
            withdrawBankresultObj = jsonObject.getJSONObject("result");
            bankName = withdrawBankresultObj.getString("bankName");
        } catch (Exception e) {
            log.error("=====米联进件 mlQuickReister 查询银行卡信息出错");
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "查询银行卡信息有误");
            resultMap.put("channel_type", "milian_quick");
            return resultMap;
        }

        // --- check random shops
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/query/randomshopid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        String randomShopId;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            jsonObject = JSONObject.fromObject(result);
            randomShopId = jsonObject.getString("result");
        } catch (Exception e1) {
            log.error(" ===米联进件 mlQuickReister 随机获取的 shopId出错！！！！" + e1.getMessage());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "进件商户失败");
            return resultMap;
        }
        log.info("随机获取的 shopId:" + randomShopId);
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/shops/query/shopid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("shopid", randomShopId);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("shop info by shopId RESULT================" + result);
        JSONObject shopInfoResultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            shopInfoResultObj = jsonObject.getJSONObject("result");
        } catch (Exception e1) {
            log.error(" 米联进件 mlQuickReister 查询商铺信息出错！！！！shopId:" + randomShopId + e1.getMessage());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "用户进件失败");
            return resultMap;
        }

        /**获取银行编号*/
        restTemplate=new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/number/name";
        requestEntity  = new LinkedMultiValueMap<String, String>();
        requestEntity.add("bank_name", bankName);
        JSONObject bankCodeResultObj;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            log.info("米联进件 mlQuickReister 获取银行编号 RESULT================"+result);
            jsonObject =  JSONObject.fromObject(result);
            bankCodeResultObj  =  jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("获取银行编号出错啦========"+e.getMessage());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "获取银行编号出错啦");
            return resultMap;
        }

        // 根据银行名称获取银行编码
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bankcode/getcodebyname";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("name", bankName);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("米联进件 mlQuickReister 获取银行编码RESULT================" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
        } catch (Exception e) {
            log.error("米联进件 mlQuickReister -- 根据银行名称获取银行编码失败 bankName:" + bankName + e.getMessage());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "根据银行名称获取银行编码失败");
            return resultMap;
        }
        // 银行编号
        String withdrawBankCode = jsonObject.getString("result");

        log.info("米联进件 mlQuickReister 开始检查进件相关数据 -- ");
        String orderExtraFeeStr = extraFee; // 代付费 (每笔)
        String rateVal = rate;  // 费率
        String userPhone = userResultObj.getString("phone");
        String withdrawBankUserName = withdrawBankresultObj.getString("userName");
        String withdrawBankCardNo = withdrawBankresultObj.getString("cardNo");
        String withdrawBankIdCard = withdrawBankresultObj.getString("idcard"); // 身份证
        String withdrawBankPhone = withdrawBankresultObj.getString("phone");
        String withdrawBankName = withdrawBankresultObj.getString("bankName");
        String shopName = shopInfoResultObj.getString("name");
        String shopAddress = shopInfoResultObj.getString("shopsaddress");
        //信用卡银行编号
        String bankCardNumberVal =  bankCodeResultObj.getString("bankNumber");

        MiLianReginsterBean miLianReginsterBean = new MiLianReginsterBean();
        miLianReginsterBean.setOrderId(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        miLianReginsterBean.setParent(parent);
        miLianReginsterBean.setFutureMinAmount("0"); // 保底 目前没有用
        miLianReginsterBean.setDebitCapAmount("9999"); // 封顶 目前没有用
        BigDecimal countFeeT0 = new BigDecimal(orderExtraFeeStr).multiply(new BigDecimal("100")); // 单位转成分, 元->分
        miLianReginsterBean.setCountFeeT0(countFeeT0.stripTrailingZeros().toPlainString());
        miLianReginsterBean.setDebitRate(rateVal);
        /*下面三个值为空字符串可以进件成功，已测过*/
        miLianReginsterBean.setBankProvince(" ");
        miLianReginsterBean.setBankCity(" ");
        miLianReginsterBean.setBankChannelNo(" ");

        miLianReginsterBean.setTelNo(withdrawBankPhone);
        miLianReginsterBean.setBankAccountName(withdrawBankUserName);
        miLianReginsterBean.setBankAccountNo(withdrawBankCardNo);
        miLianReginsterBean.setLegalPersonIdcard(withdrawBankIdCard);
        miLianReginsterBean.setPhoneNo(withdrawBankPhone);
        miLianReginsterBean.setSettBankName(withdrawBankName);
        miLianReginsterBean.setBankAbbr(withdrawBankCode);
        miLianReginsterBean.setBankCode(bankCardNumberVal);
        miLianReginsterBean.setBankSubName(withdrawBankName);
        miLianReginsterBean.setHandleType(handleType);  // A 新增进件  M 修改进件
        miLianReginsterBean.setMerchName(withdrawBankUserName);
		miLianReginsterBean.setMerchAbb(shopName.length() > 10 ? shopName.substring(0, 10) : shopName);// 中文不超过10
        miLianReginsterBean.setMerchAddress(shopAddress);
        /*随机经营类目*/
        miLianReginsterBean.setCategory(getCategory());

        if(handleType.equals("M")){
            MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId),bankNumber);
            miLianReginsterBean.setChangeType("M03");
            miLianReginsterBean.setMerchId(miLianQuickRegister.getMerchantNo());
        }

        String params = ParamsUtil.getBaseMerchRegisterParams(miLianReginsterBean , key);
        log.info("米联进件 mlQuickReister 开始请求进件参数={} :" ,params);
        String respResult = HttpHelper.doHttp(RegisterUrl, HttpHelper.POST, "UTF-8", params, "60000");
        log.info("米联进件 mlQuickReister 开始请求进件结果={} :" ,respResult);
        MilianBaseResMessage<MiLianMerchan> res = com.alibaba.fastjson.JSONObject.parseObject(respResult, new TypeReference<MilianBaseResMessage<MiLianMerchan>>() {
        });

        log.info("米联进件 mlQuickReister 请求入驻接口响应内容：" + res.getRespMsg());
        if ("0000".equals(res.getRespCode())) {
            log.info("米联进件 mlQuickReister 进件成功后处理开始 ");
            MiLianQuickRegister miLianQuickRegister = new MiLianQuickRegister();
            miLianQuickRegister.setUserId(Long.parseLong(userId));
            miLianQuickRegister.setBankCard(withdrawBankCardNo);
            miLianQuickRegister.setDebitRate(rate);
            miLianQuickRegister.setName(withdrawBankName);
            miLianQuickRegister.setIdNo(withdrawBankIdCard);
            miLianQuickRegister.setCountFee(orderExtraFeeStr);
            /*判断新进件还是修改进件*/
            if(handleType.equals("M")){
                log.info("米联进件---mlQuickReister---修改进件a");
                MiLianQuickRegister orginRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userId),bankNumber);
                miLianQuickRegister.setState("Y");
                miLianQuickRegister.setMerchantNo(orginRegister.getMerchantNo());
                miLianQuickRegister.setMerchantKey(orginRegister.getMerchantKey());
                topupPayChannelBusiness.deleteMiLianRegisterByUIdAndBankId(Long.valueOf(userId),bankNumber);
                log.info("米联进件---mlQuickReister---修改进件b");
            }else {
                log.info("米联进件---mlQuickReister---新增进件");
                miLianQuickRegister.setMerchantNo(res.getData().getMerchantNo());// 商户号/商户key只有在新增进件才会返回
                miLianQuickRegister.setMerchantKey(res.getData().getMerchantKey());
                miLianQuickRegister.setState("N");

            }
            MiLianQuickRegister resultMLQuickRegister = topupPayChannelBusiness.createMiLianQuickRegister(miLianQuickRegister);
            log.info("米联进件 mlQuickReister 保存数据库======result====="+resultMLQuickRegister);
            log.info("米联进件 mlQuickReister 保存数据库成功, t_ml_register" + " mlDataId:" + resultMLQuickRegister.getId());
            log.info("米联进件 mlQuickReister --------OK----------");
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            resultMap.put(CommonConstants.RESP_MESSAGE, "进件成功");
            //resultMap.put(CommonConstants.RESULT, resultMLQuickRegister);
            return resultMap;
        }else {
            log.info("米联进件 mlQuickReister 进件失败====== "  + " RespCode:" + res.getRespCode() + " msg:" + res.getRespMsg());
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, res.getRespMsg());
            return resultMap;
        }

    }

    /*随机获取category经营项目*/
    public static String getCategory(){
//        String categoryString = "{\"4900\":\"公共事业\",\"5831\":\"饮酒场所\",\"5812\":\"就餐场所和餐馆\",\"7997\":\"会员俱乐部\",\"7298\":\"健美及美容SPA\",\"7032\":\"运动和娱乐露营地\",\"5094\":\"贵重珠宝，首饰，钟表零售\",\"1520\":\"一般承包商\",\"5933\":\"典当，拍卖，信托\",\"5511\":\"汽车经销商\",\"5499\":\"零食店\",\"5422\":\"自助加油站\",\"5411\":\"大型超市\",\"4121\":\"出租车服务\",\"4131\":\"公路客运\",\"4511\":\"航空公司\",\"5065\":\"电器零件和设备\"}";
        // 5831 饮酒场所 不支持
    	String categoryString = "{\"4900\":\"公共事业\",\"5812\":\"就餐场所和餐馆\",\"7997\":\"会员俱乐部\",\"7298\":\"健美及美容SPA\",\"7032\":\"运动和娱乐露营地\",\"5094\":\"贵重珠宝，首饰，钟表零售\",\"1520\":\"一般承包商\",\"5933\":\"典当，拍卖，信托\",\"5511\":\"汽车经销商\",\"5499\":\"零食店\",\"5422\":\"自助加油站\",\"5411\":\"大型超市\",\"4121\":\"出租车服务\",\"4131\":\"公路客运\",\"4511\":\"航空公司\",\"5065\":\"电器零件和设备\"}";

        Map<String ,String > map = com.alibaba.fastjson.JSONObject.parseObject(categoryString,Map.class);
        Object[] categorys = map.keySet().toArray();
        int index = (int) (Math.random() * categorys.length);
        return categorys[index].toString();
    }

}
